# coding:utf-8
from datetime import datetime
import os
from os import path, makedirs
from PIL import Image
import numpy as np
from wordcloud import WordCloud

# 当前文件所在目录 → services/wordcloud/
base_dir = os.path.dirname(os.path.abspath(__file__))

def generate_wordcloud_from_frequencies(
    word_freq: dict,
    output_filename: str = None,
    mask_filename: str = "ams.png",
    colormap: str = "viridis"
):
    """
    从词频字典生成词云，确保每个词只出现一次
    """
    # 资源目录（相对于 base_dir）
    images_dir = os.path.join(base_dir, 'image')
    output_dir = os.path.join(base_dir, 'output')
    font_dir = os.path.join(base_dir, 'font')
    
    for d in [images_dir, output_dir, font_dir]:
        if not path.exists(d):
            makedirs(d)
    
    # 加载 mask
    mask_array = None
    if mask_filename:
        mask_path = os.path.join(images_dir, mask_filename)
        if path.exists(mask_path):
            mask_array = np.array(Image.open(mask_path))
        else:
            print(f"警告：mask 文件 {mask_path} 不存在，将使用默认形状")

    # 字体路径
    font_path = os.path.join(font_dir, "msyh.ttf")
    if not path.exists(font_path):
        import platform
        system = platform.system()
        if system == "Darwin":
            font_path = "/System/Library/Fonts/PingFang.ttc"
        elif system == "Linux":
            font_path = "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"
        elif system == "Windows":
            font_path = "C:/Windows/Fonts/msyh.ttc"
        if not path.exists(font_path):
            raise FileNotFoundError("未找到中文字体，请将 msyh.ttf 放入 ./font/ 目录")

    # 生成词云
    wc = WordCloud(
        background_color="white",
        max_words=200,
        mask=mask_array,
        stopwords=set(),
        font_path=font_path,
        colormap=colormap,
        width=2400,
        height=1200,
        scale=2,
        random_state=42
    )
    wc.generate_from_frequencies(word_freq)

    # 保存
    if not output_filename:
        output_filename = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + ".png"
    output_path = os.path.join(output_dir, output_filename)
    wc.to_file(output_path)
    print(f"词云已保存至: {output_path}")
    return output_path